package dao

import (
	"context"
	"fmt"

	"go.mongodb.org/mongo-driver/bson"

	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
)

type Mongo struct {
	col         *mongo.Collection
	newObjectID func() primitive.ObjectID
}

func NewMongo(db *mongo.Database) *Mongo {
	return &Mongo{
		col:         db.Collection("blob"),
		newObjectID: primitive.NewObjectID,
	}
}

type BlobRecord struct {
	ID        primitive.ObjectID `bson:"_id"`
	AccountID string             `bson:"accountid"`
	Path      string             `bson:"path"`
}

func (m *Mongo) CreateBlob(c context.Context, accountID string) (*BlobRecord, error) {
	objID := primitive.NewObjectID()
	br := &BlobRecord{
		ID:        objID,
		AccountID: accountID,
	}

	br.Path = fmt.Sprintf("%s/%s", accountID, objID.Hex())

	_, err := m.col.InsertOne(c, br)
	if err != nil {
		return nil, err
	}

	return br, nil
}

func (m *Mongo) GetBlob(c context.Context, blobID string) (*BlobRecord, error) {
	objID, _ := primitive.ObjectIDFromHex(blobID)
	res := m.col.FindOne(c, bson.M{
		"_id": objID,
	})

	if res.Err() != nil {
		return nil, res.Err()
	}

	br := BlobRecord{}

	err := res.Decode(&br)
	if err != nil {
		return nil, fmt.Errorf("can not decode result: %v", err)
	}

	return &br, nil
}
